package com.dailywork.basepro.thread;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * SimpleDateFormat线程不安全
 *
 * @author think
 * @version 1.0.0
 * @since 2020/4/26
 */
public class ThreadNoSafe1 implements Runnable {
    private static ThreadLocal<SimpleDateFormat> local = new ThreadLocal<>();

    private String name;
    private String dateStr;

    public ThreadNoSafe1(String name, String dateStr) {
        this.name = name;
        this.dateStr = dateStr;
    }

    @Override
    public void run() {

        try {
            SimpleDateFormat df = local.get();
            if (Objects.isNull(df)) {
                df = new SimpleDateFormat("yyyy-mm-dd");
                local.set(df);
            }
            Date date = df.parse(dateStr);
            System.out.println(name + ": date:" + date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        executorService.execute(new ThreadNoSafe1("A", "2017-06-10"));
        executorService.execute(new ThreadNoSafe1("B", "2016-06-06"));
        executorService.shutdown();
    }
}
